/*********************************************************************************
 * File Name: MessageDBImpl.java
 * Package Name: com.sensorfriendly.provider.impl
 * 
 * Purpose:
 * The implementation of the Messages in the DB
 *  
 *********************************************************************************/

package com.sensorfriendly.provider.impl;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;

import com.sensorfriendly.model.Message;


public class MessageDBImpl {
	public Context mContext;
	
	// Constructor
	public MessageDBImpl(Context context){
		mContext=context;
	}

	// Insert the message into the DB if it doesnt
	// already exist
	public boolean insertMessage(Message message){
		if (!exists(message)) {
			ContentResolver resolver = mContext.getContentResolver();
			ContentValues value = getQueryValues(message);
			resolver.insert(MessageTable.CONTENT_URI, value);
			return true;
		}
		return false;
	}

	// Returns a list of messages for the given Scenario Name
	// from the Database
	public List<Message> getMessagesForScenario(String scenarioName) {
		List<Message> messages = new ArrayList<Message>();
		ContentResolver resolver = mContext.getContentResolver();
		String where = MessageTable.PARENT_SCENARIO_NAME + "="+DatabaseUtils.sqlEscapeString(scenarioName);
		Cursor cursor =resolver.query(MessageTable.CONTENT_URI, null, where, null, null);
		while (cursor != null && cursor.getCount() > 0 && !cursor.isLast()){
			Message item =  fillFromCursor(cursor);
			messages.add(item);
		}
		return messages;
	}
	
	// Fetch a particular given Message for thr input Scenario
	public Message getMessage(String scenario, String message) {
		ContentResolver resolver = mContext.getContentResolver();
		String	where= MessageTable.MESSAGE_CONTENT +" = "+ DatabaseUtils.sqlEscapeString(message) + " and "
				+ MessageTable.PARENT_SCENARIO_NAME + "=" + DatabaseUtils.sqlEscapeString(scenario);
		Cursor cursor =resolver.query(MessageTable.CONTENT_URI, null, where, null, null);
		Message item = null;
		if (cursor != null && cursor.getCount() > 0 && !cursor.isLast()){
			item =  fillFromCursor(cursor);
		}
		return item;
	}
	

	// Update the Old Message with the new one
	// in the DB
	public void updateMessage(String oldContent, Message message) {
		ContentResolver resolver = mContext.getContentResolver();
		String	where= MessageTable.MESSAGE_CONTENT +" = "+ DatabaseUtils.sqlEscapeString(oldContent) + " and "
				+ MessageTable.PARENT_SCENARIO_NAME + "=" + DatabaseUtils.sqlEscapeString(message.getScenarioName()) ;
		ContentValues fields = getQueryValues(message);
		resolver.update(MessageTable.CONTENT_URI, fields, where, null);		
	}
	
	// Delete the given message from the DB 
	public int deleteMessage(Message message){
		ContentResolver resolver = mContext.getContentResolver();
		String	where= MessageTable.MESSAGE_CONTENT +" = "+ DatabaseUtils.sqlEscapeString(message.getMessageContent()) + " and "
				+ MessageTable.PARENT_SCENARIO_NAME + "=" + DatabaseUtils.sqlEscapeString(message.getScenarioName()) ;
		return resolver.delete(MessageTable.CONTENT_URI, where, null);
	}
	
	// Delete all the messages under the given Scenario
	// from the DB
	public int deleteMessageForScenario(String scenarioName){
		ContentResolver resolver = mContext.getContentResolver();
		String	where= MessageTable.PARENT_SCENARIO_NAME + "=" + DatabaseUtils.sqlEscapeString(scenarioName) ;
		return resolver.delete(MessageTable.CONTENT_URI, where, null);
	}
	
	// Fill the cursor with next set of messages
	public Message fillFromCursor(Cursor cursor){
		cursor.moveToNext();
		Message message = new Message();
		message.setAudioFile(cursor.getString(cursor.getColumnIndex(MessageTable.AUDIO_FILE_NAME)));
		message.setMessageContent(cursor.getString(cursor.getColumnIndex(MessageTable.MESSAGE_CONTENT)));
		message.setMessageImagePath(cursor.getString(cursor.getColumnIndex(MessageTable.MESSAGE_IMAGE_NAME)));
		message.setScenarioName(cursor.getString(cursor.getColumnIndex(MessageTable.PARENT_SCENARIO_NAME)));
		message.setTimeCreated(cursor.getLong(cursor.getColumnIndex(MessageTable.TIME_POSTED)));
		return message;
	}
	
	

	private ContentValues getQueryValues(Message message){
		ContentValues value = new ContentValues();
		Long time;
		if((time=message.getTimeCreated()) == null){
			time = System.currentTimeMillis();
		}
		value.put(MessageTable.TIME_POSTED, time);
		value.put(MessageTable.MESSAGE_CONTENT,  message.getMessageContent());
		value.put(MessageTable.AUDIO_FILE_NAME, message.getAudioFile());
		value.put(MessageTable.MESSAGE_IMAGE_NAME, message.getMessageImagePath());
		value.put(MessageTable.PARENT_SCENARIO_NAME, message.getScenarioName());
		return value;
	}
	
	// Check if the given Message existts in the DB
	// or not
	private boolean exists(Message message){
		ContentResolver resolver = mContext.getContentResolver();
		String	where= MessageTable.MESSAGE_CONTENT +" = "+ DatabaseUtils.sqlEscapeString(message.getMessageContent()) + " and "
				+ MessageTable.PARENT_SCENARIO_NAME + "=" + DatabaseUtils.sqlEscapeString(message.getScenarioName()) ;
		Cursor cursor =resolver.query(MessageTable.CONTENT_URI, null, where, null, null);
		if(cursor == null){
			return false;
		}
		boolean exists = !(cursor.getCount()==0);
		safelyCloseCursor(cursor);
		return exists;
	}

	// Close the cursor safely
	private void safelyCloseCursor(Cursor cur) {
		if(cur != null && cur.isClosed() == false)
			cur.close();
	}
	
}
